import 'package:sqflite/sqflite.dart';

/// sqflite封装
class DatabaseHelper {
  static Database? _database;
  static const String dbName = 'net_base_data_database.db';
  static const String tableName = 'net_base_data_table';

  Future<Database> get database async {
    if (_database != null) return _database!;

    // 如果数据库尚未初始化，则初始化数据库
    _database = await initDatabase();
    return _database!;
  }

  Future<Database> initDatabase() async {
    String databasesPath = await getDatabasesPath();
    return await openDatabase('$databasesPath/$dbName',
        version: 1, onCreate: _createTable);
  }

  Future<void> _createTable(Database db, int version) async {
    await db.execute('''
      CREATE TABLE $tableName (
        id INTEGER PRIMARY KEY, 
        key TEXT,
        value TEXT
      )
    ''');
    //INTEGER PRIMARY KEY 的语法表示创建一个整数类型的主键，并且会自动递增
  }

  /// 插入
  Future<int> set(String key, String value) async {
    Database db = await database;
    List<Map<String, Object?>> result =
        await db.query(tableName, where: 'key = ?', whereArgs: [key]);
    if (result.isNotEmpty) {
      return await db.update(tableName, {'key': key, 'value': value},
          where: 'key = ?', whereArgs: [key]);
    } else {
      return await db.insert(tableName, {'key': key, 'value': value});
    }
  }

  /// 获取
  Future<String> get(String key) async {
    Database db = await database;
    List<Map<String, Object?>> result =
        await db.query(tableName, where: 'key = ?', whereArgs: [key]);
    if (result.isEmpty) {
      return '';
    } else {
      return result[0]['value'].toString();
    }

    //where的参数应该和whereArgs的参数相对应,放着sql被注入
  }

  /// 删除
  Future<int> delete(int key) async {
    Database db = await database;
    return await db.delete(tableName, where: 'key = ?', whereArgs: [key]);
  }
}
